#include "ThreadObject.h"
#ifdef Q_OS_WIN32
#include <windows.h>
#endif
#include <QThread>
#include <QDebug>
#include <QMutexLocker>
#include <QElapsedTimer>
#include <limits>
#include "DesignModel.h"

ThreadObject::ThreadObject(DesignModel *model) : QObject(0), m_model(model), m_isStop(true)
{
}

ThreadObject::~ThreadObject()
{
    // qDebug() << "ThreadObject destroy";
}

int getKeyformStr(QString keyString)
{
    int key = 0;
    if (keyString.count() == 1) // 单字符
    {
        key = int(keyString.toUpper().toUtf8().at(0));
        qInfo() << "key is" << key << char(key);
    }
    else if (keyString.count() > 0 && keyString.toUpper().toUtf8().at(0) == 'F') // F1 F2 F3 ...
    {
        QString str = keyString.right(keyString.count() - 1);
#ifdef Q_OS_WIN32
        key = VK_F1 + str.toInt() - 1;
#endif
        qInfo() << "key is" << key << keyString;
    }
    return key;
}

void ThreadObject::runKeyLaunchWork()
{
    {
        QMutexLocker locker(&m_stopMutex);
        m_isStop = false;
    }
    while (1)
    {
        if (m_model->keyMode() == 0) // sequence
        {
            QStringList keyStrList = m_model->sequenceKey().split(" ");
            for (int i = 0; i < keyStrList.count(); i++)
            {
                {
                    QMutexLocker locker(&m_stopMutex);
                    if (m_isStop)
                    {
                        qInfo() << "sequence over";
                        emit finished();
                        return;
                    }
                }
                if (keyStrList.at(i).count() <= 0)
                {
                    continue;
                }
#ifdef Q_OS_WIN32
                keyDownUp(getKeyformStr(keyStrList.at(i)));
                Sleep(m_model->interval().toInt()); // xx ms
#endif
            }
        }
        else if (m_model->keyMode() == 1) // batter
        {
            for (int i = 0; i < m_model->stopKey().toInt(); i++) // batter count
            {
                {
                    QMutexLocker locker(&m_stopMutex);
                    if (m_isStop)
                    {
                        qInfo() << "switch disenable batter over";
                        emit finished();
                        return;
                    }
                }
#ifdef Q_OS_WIN32
                keyDownUp(getKeyformStr(m_model->startKey()));
                Sleep(m_model->interval().toInt()); // xx ms
#endif
            }
            qInfo() << "batter over";
            m_model->setRunning(false);
            emit finished();
            return;
        }
    }
}

void ThreadObject::stop()
{
    QMutexLocker locker(&m_stopMutex);
    m_isStop = true;
}
